<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>按钮点击次数统计</title>
    <!-- 引入 ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
</head>
<body>
    <h1>按钮点击次数统计</h1>
    <!-- 按钮 -->
    <button id="button1">按钮1</button>
    <button id="button2">按钮2</button>
    <button id="button3">按钮3</button>
    <!-- 重置按钮 -->
    <button id="resetButton" style="margin-top: 20px; font-size: 1.5em; padding: 10px 20px; background-color: red; color: white; border: none; border-radius: 5px; cursor: pointer;">
        重置计数
    </button>

    <!-- 柱状图容器 -->
    <div id="chart" style="width: 600px;height:400px;"></div>

    <script>
        // 初始化 ECharts 图表
        var chart = echarts.init(document.getElementById('chart'));

        // 初始化图表数据
        var buttonCounts = {
            button1: 0,
            button2: 0,
            button3: 0
        };

        // 设置图表选项
        var option = {
            title: {
                text: '按钮点击次数统计'
            },
            tooltip: {},
            xAxis: {
                data: ['按钮1', '按钮2', '按钮3']
            },
            yAxis: {},
            series: [{
                name: '点击次数',
                type: 'bar',
                data: [0, 0, 0]
            }]
        };

        // 渲染图表
        chart.setOption(option);

        // 按钮点击事件
        document.getElementById('button1').addEventListener('click', function () {
            updateCount('button1');
        });
        document.getElementById('button2').addEventListener('click', function () {
            updateCount('button2');
        });
        document.getElementById('button3').addEventListener('click', function () {
            updateCount('button3');
        });

        // 重置按钮点击事件
        document.getElementById('resetButton').addEventListener('click', function () {
            resetCounts();
        });

        // 更新按钮点击次数并更新图表
        async function updateCount(buttonId) {
            try {
                // 调用后端 API 更新数据库（使用POST请求）
                const response = await fetch(`/update-count/${buttonId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ buttonId: buttonId })
                });
                const data = await response.json();

                // 更新本地数据
                buttonCounts[buttonId] = data.count;

                // 更新图表数据
                chart.setOption({
                    series: [{
                        data: [
                            buttonCounts.button1,
                            buttonCounts.button2,
                            buttonCounts.button3
                        ]
                    }]
                });
            } catch (error) {
                console.error('更新失败:', error);
            }
        }

        // 重置按钮点击次数
        async function resetCounts() {
            try {
                // 调用后端 API 重置数据库中的计数
                const response = await fetch('/reset-counts', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                const data = await response.json();

                // 重置本地数据
                buttonCounts.button1 = 0;
                buttonCounts.button2 = 0;
                buttonCounts.button3 = 0;

                // 重置图表数据
                chart.setOption({
                    series: [{
                        data: [0, 0, 0]
                    }]
                });

                alert('计数已重置');
            } catch (error) {
                console.error('重置失败:', error);
            }
        }

        // 每30秒同步一次数据
        setInterval(syncData, 30000);

        // 同步数据到后端
        async function syncData() {
            try {
                // 获取最新的数据
                const response = await fetch('/get-counts');
                const data = await response.json();

                // 更新本地数据
                buttonCounts.button1 = data.button1;
                buttonCounts.button2 = data.button2;
                buttonCounts.button3 = data.button3;

                // 更新图表数据
                chart.setOption({
                    series: [{
                        data: [
                            buttonCounts.button1,
                            buttonCounts.button2,
                            buttonCounts.button3
                        ]
                    }]
                });

                console.log('数据同步完成');
            } catch (error) {
                console.error('数据同步失败:', error);
            }
        }

        // 页面加载时获取初始数据
        async function loadInitialData() {
            try {
                const response = await fetch('/get-counts');
                const data = await response.json();

                // 更新本地数据
                buttonCounts.button1 = data.button1;
                buttonCounts.button2 = data.button2;
                buttonCounts.button3 = data.button3;

                // 更新图表数据
                chart.setOption({
                    series: [{
                        data: [
                            buttonCounts.button1,
                            buttonCounts.button2,
                            buttonCounts.button3
                        ]
                    }]
                });
            } catch (error) {
                console.error('加载初始数据失败:', error);
            }
        }

        // 加载初始数据
        loadInitialData();
    </script>
</body>
</html>